<?php
/**
* 
*/
class GetUserinfoAction extends Action
{
	
  	public function index()
	{
		if(isset($_GET['code'])){
			$code = $_GET['code'];
			//var_dump($code);
			$info = $this->getInfo($code);
			//dump($info);
			$ret = M('user')->where(array('openid'=>$info['openid']))->select();
			dump($ret);
			if($ret){
				$this->show('您近期已经授权登录了');
				setcookie("wid", $ret[0]['id'], time() + 10 * 365 * 24 * 60 * 60);
				session('id',$ret[0]['id']);
				//dump(session('id'));
			}else{
			//dump($info);die;
			$this->assign('info',$info);
			$this->display();
		}
		}else{
			$this->display();
		}

	}
	public function code(){
		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9d8f3d6a105a7b28&redirect_uri=http%3A%2F%2Faaa.17wsx.com/index.php/GetUserinfo/getcode&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
	}
	public function getcode(){

		
		$code = file_get_contents($url);
		dump($code);
	}

	public function getInfo($code){
	@header('Content-type:text/html;charset=utf-8');
	$appid = "wx9d8f3d6a105a7b28";
	$appsecret = "9638441d52c7b712637ead74d0922401";
	$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
	$access_token_json = $this->https_request($access_token_url);
	$access_token_array = json_decode($access_token_json,true);
	//var_dump($access_token_array);
	$openid = $access_token_array['openid'];
	$access_token = $access_token_array['access_token'];
	//return $appsecret;
	$userinfo_url ="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
	$userinfo_json = $this->https_request($userinfo_url);
	$userinfo_array = json_decode($userinfo_json,true);
	return $userinfo_array;
	}
	public function https_request($url){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($cur,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$data = curl_exec($ch);
		if(curl_errno($ch)){
			return 'error'.curl_error($ch);
		}
		return $data;
		curl_close($ch);
	}
	public function adduser(){
		$data = I('post.','');
		$data['password'] = md5($data['password']);
		$username = $data['username'] = trim($data['username']);
		//dump($data);
		$openid = $data['openid'];
		$res = M('user')->where(array('openid'=>$openid))->find();
		if($res){
			$this->error('对不起，该微信号已绑定账号，如有需要请先解绑');
		}else{
			//dump($username);
			$ret = M('user')->where(array('username'=>$username))->find();
			//dump($ret);die;
			if($ret){
				if($ret['password'] ==$data['password']){
					$rett = M('user')->where(array('id'=>$ret['id']))->save($data);
					if($rett){
						setcookie('wid', $ret['id'], time() + 10 * 365 * 24 * 60 * 60);
						//dump($_COOKIE['wid']);die;
						$this->success('绑定成功');
					}
				}else{
					$this->error('密码错误');
				}
			}else{
				$this->error('账号不存在，请检查');
			}
		}
	}
}
?>